package net.cathackers.devel.scmp.chat.impl.xmpp;

import net.cathackers.devel.scmp.chat.interfaces.ChatManager;
import net.cathackers.devel.scmp.chat.interfaces.ChatSession;
import net.cathackers.devel.scmp.chat.interfaces.XMPPConnection;
import net.cathackers.devel.scmp.config.impl.SCMPConstants;
import net.cathackers.devel.scmp.factories.SCMPFactory;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class ConnectionHandler extends IoHandlerAdapter {
    ChatManager manager_;
    Logger      logger_;

    public ConnectionHandler() {
        this.manager_ = SCMPFactory.getChatManager();
        logger_ = SCMPFactory.getLogger(this);
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
	logger_.debug("Message received: " + (String) message);
        XMPPProtocolParser parser = (XMPPProtocolParser) session.getAttribute("HANDLER");
        parser.process((String) message);
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
	logger_.debug("Message Sent...<" + message.toString() + ">");
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        session.setAttribute(SCMPConstants._PARSER_, new XMLCumulativeParser());
        XMPPConnection connection = new XMPPConnectionImpl(session);
        session.setAttribute("HANDLER", new XMPPProtocolParser(SCMPFactory.getConfiguration().getChatServerDomain(), connection));
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        logger_.error("Exception Occured while receiving data:" + cause.getMessage());
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
	logger_.info("Session IDLE");
	try {
		XMPPProtocolParser parser = (XMPPProtocolParser)session.getAttribute("HANDLER");
		String sessionID = parser.getConnection().getSessionID();
		ChatManager manager = SCMPFactory.getChatManager(); 
		manager.destroySession(sessionID);
		ChatSession sess = manager.getChatSession(sessionID);
		sess.bye();
	}catch (Exception e) {}
	logger_.info("Session CLOSED");        
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
	// make sure that we removed this session from the cache...
	try {
        	XMPPProtocolParser parser = (XMPPProtocolParser)session.getAttribute("HANDLER");
        	String sessionID = parser.getConnection().getSessionID();
        	logger_.debug("Destroying this session " + sessionID);
        	ChatManager manager = SCMPFactory.getChatManager(); 
        	manager.destroySession(sessionID);
      
	}catch (Exception e) {}
	logger_.info("Session CLOSED");
    }

}
